<?php

namespace App\Http\Controllers\Sys_api;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Config;
use Icharle\Wxtool\Wxtool;
use Yansongda\Pay\Pay;
use Yansongda\Pay\Log;

/**
 * base
 */
// 跨域问题解决方案
header("Access-Control-Allow-Origin:*");
class BaseAPIController extends Controller
{

    protected $pageSize = 20;
    

    public function __construct()
    {
        // 初始化系统常量
        $this->initSystemConst();
   
    }


    /** 
     * 初始化系统常量
     * @return void
     * @author VJF
     * 
     */
    private function initSystemConst()
    {
        
        
    }

    /**
     * 渲染layui.table
     * @param array $list 查询后的分页数组
     */
    public function rjson($list = [])
    {
        $arr['code'] = 1;
        $arr['msg'] = "OK";
        $arr['count'] = $list['total'] ?: 0;
        $arr['data'] = $list['data'] ?: [];
        // $arr['datas'] = $list ?: [];
        return json_encode($arr);
    }

    /**
     * 获取纬度范围
     *
     * @param [type] $distance
     * @param [type] $latitude
     * @return void
     */
    public static function GetMaxOrMinLat($distance, $latitude)
    {
        $range  = 180 / pi() * $distance / 6378.138; //搜索 N km 之内
        $maxLat = $latitude + $range; //最大纬度
        $minLat = $latitude - $range; //最小纬度
        $latArr = [
            'minLat' => $minLat,
            'maxLat' => $maxLat
        ];
        return $latArr;
    }


    /**
     * 获取精度范围
     *
     * @param [type] $distance
     * @param [type] $latitude
     * @param [type] $longitude
     * @return void
     */
    public static function GetMaxOrMinLng($distance, $latitude, $longitude)
    {
        $range  = 180 / pi() * $distance / 6378.138; //搜索 N km 之内
        $lngR   = $range / cos($latitude * pi() / 180);
        $maxLng = $longitude + $lngR; //最大经度
        $minLng = $longitude - $lngR; //最小经度
        $lngArr = [
            'minLng' => $minLng,
            'maxLng' => $maxLng
        ];
        return $lngArr;
    }


    /**
     * 根据起点坐标和终点坐标测距离
     * @param  [array]   $from     [起点坐标(经纬度),例如:array(118.012951,36.810024)]
     * @param  [array]   $to     [终点坐标(经纬度)]
     * @param  [bool]    $km        是否以公里为单位 false:米 true:公里(千米)
     * @param  [int]     $decimal   精度 保留小数位数
     * @return [string]  距离数值
     */
    public static function getDistanceBy2Point($from, $to, $km = true, $decimal = 2)
    {
        sort($from);
        sort($to);
        $EARTH_RADIUS = 6378.138; // 地球半径系数
        $distance = $EARTH_RADIUS * 2 * asin(sqrt(pow(sin(($from[0] * pi() / 180 - $to[0] * pi() / 180) / 2), 2) + cos($from[0] * pi() / 180) * cos($to[0] * pi() / 180) * pow(sin(($from[1] * pi() / 180 - $to[1] * pi() / 180) / 2), 2))) * 1000;
        if ($km && $distance > 1000) {
            return round($distance / 1000, 2) . 'km';
        }
        return round($distance, $decimal) . 'm';
    }

    /**
     * 二维数组排序
     *
     * @param [type] $arr
     * @param [type] $field
     * @param [type] $sort
     * @return void
     */
    public static function arraySort($arr, $field, $sort = SORT_ASC)
    {
        $key = array_column($arr, $field);
        array_multisort($key, $sort, $arr);
        return $arr;
    }



    /**
     * 获取用户信息
     *
     * @param [type] $code
     * @param [type] $iv
     * @param [type] $encryptedData
     * @return void
     */
    public static function GetWxInfo($code, $iv, $encryptedData)
    {
        $a = new Wxtool();
        $res = $a->GetSessionKey($code);                            //获取用户openid 和 session_key
        // $userinfo = $a->GetUserInfo($encryptedData, $iv);            //获取用户详细信息
        // dd($userinfo);
        return ($res);
    }

    /**
     * 生成订单号
     *
     * @return void
     */
    public function getOrderId()
    {
        //日期:10位 timestamp
        $datetime = time();
        //随机数
        $newnum = $this->getNonceNums();
        return $datetime . $newnum;
    }

    /**
     * 生成随机数
     *
     * @param integer $numLen
     * @return void
     */
    public function getNonceNums($numLen = 4)
    {
        $chars = "0123456789";
        $str = "";
        for ($i = 0; $i < $numLen; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /*
    * 生成随机字符串方法
    */
    protected function createNoncestr($length = 32)
    {
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

     //将xml字符串转换为数组
     protected static function xmlToArray($xml)
     {
         $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
         return $array_data;
     }

     
    /*
    *排序并格式化参数方法，签名时需要使用
    */
    protected function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if ($urlencode) {
                $v = urlencode($v);
            }
            //$buff .= strtolower($k) . "=" . $v . "&";
            $buff .= $k . "=" . $v . "&";
        }
        $reqPar = "";
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff)-1);
        }
        return $reqPar;
    }
    
      
     /*
     * 对要发送到微信统一下单接口的数据进行签名
     */
     protected function getSign($Obj, $apiKey)
     {
         foreach ($Obj as $k => $v) {
             $param[$k] = $v;
         }
         //签名步骤一：按字典序排序参数
         ksort($param);
         $String = $this->formatBizQueryParaMap($param, false);
         //签名步骤二：在string后加入KEY
         $String = $String."&key=" . $apiKey;
         //签名步骤三：MD5加密
         $String = md5($String);
         //签名步骤四：所有字符转为大写
         $result_ = strtoupper($String);
         return $result_;
     }

     //php请求网络的方法
    public function curl_get($url, &$httpCode = 0)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    
        //不做证书校验,部署在linux环境下请改为true
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $file_contents = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $file_contents;
    }

     //小程序登录
    public function wechat_min_login($appid, $appsecret, $code)
    {
        $wxUrl = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code';
        $getUrl = sprintf($wxUrl, $appid, $appsecret, $code);//把appid，appsecret，code拼接到url里
        $result = $this->curl_get($getUrl);//请求拼接好的url
        $wxResult = json_decode($result, true);
        
        if (isset($wxResult['errcode'])) {
            print_r($wxResult['errmsg']);
        }
        return $wxResult;
    }

    //获取openid
    public function wxPay($wxCode, $uid )
    {
        $options = Config::get("easywechat");
        $appid = $options["mini_app"]["default"]["app_id"];
        $appsecret = $options["mini_app"]["default"]["secret"];
        $result = $this->wechat_min_login($appid, $appsecret, $wxCode);
        dd($result);
        $openid = $result["openid"];
        return $openid;
    }
}
